package com.zmyuan.demo.netty.thrift.utils;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;

import java.lang.reflect.Method;

/**
 * Created by zdb on 2017/2/17.
 */
public class ThriftUtils {

    /**
     * 将byte[]转换为Thrift对象
     * @param bytes
     * @param tClass
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T>T  convertBytesToObject(byte[] bytes, Class<T> tClass) throws Exception {
        TMemoryBuffer buffer = new TMemoryBuffer(1024);
        buffer.write(bytes);

        TProtocol prot = new TBinaryProtocol(buffer);

        T obj = tClass.newInstance();
        Method readMethod = tClass.getMethod("read", org.apache.thrift.protocol.TProtocol.class);
        readMethod.invoke(obj, prot);

//        Content c = new Content();
//        c.read(prot);

        return obj;
    }

    /**
     * 将Thrift对象转换成byte[]
     * @param obj
     * @return
     * @throws Exception
     */
    public static byte[] convertThriftObjToBytes(Object obj) throws Exception {
        TMemoryBuffer buffer = new TMemoryBuffer(1024);
        TProtocol prot = new TBinaryProtocol(buffer);
        Method writeMethod = obj.getClass().getMethod("write", TProtocol.class);
        writeMethod.invoke(obj, prot);
//        Msg msg = new Msg();
//        msg.write(prot);
        return buffer.getArray();
    }
}
